package network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;


public class TCPListener extends Thread{

	Socket sock;
	byte[] buf;
	ChatNI netwInt;
	String fileSavePath;
	
	public TCPListener(ChatNI father, String savePath, ServerSocket socket) {
		try {
			sock = socket.accept();
		} catch (IOException e) {
			e.printStackTrace();
		}
		netwInt = father;
		this.fileSavePath=savePath;
		buf = new byte [2048];
		
	}
	
	public void run () {
		while (sock.isClosed()!=true) {
			receiveData();
		}
		netwInt.dlComplete(sock.getInetAddress());
	}
	
	
	public void receiveData (){
		int i;
		try {
			//File fi = new File(fileSavePath);
			//fi.createNewFile();
			FileOutputStream f = new FileOutputStream(fileSavePath);
			InputStream inp = sock.getInputStream();
			while ((i=inp.read(buf))!=-1) {
				f.write(buf, 0, i);
			}
			//f.flush();
			
			inp.close();
			f.close();
			sock.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
}
